﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using System.Xml.Linq;

using BLL;

namespace CTRL
{
    public class CtrlJumper
    {
        private static CtrlJumper instance = null;
        private static readonly object padlock = new object();
        private static readonly string jumperFile = String.Format("{0}\\{1}", System.IO.Directory.GetCurrentDirectory(), "jumpers.xml");

        List<Jumper> jumperList;
        CtrlCountry ctrlCountry;

        public CtrlJumper()
        {
            jumperList = new List<Jumper>();
            ctrlCountry = CtrlCountry.Instance;
            LoadJumperFile();
        }

        public List<Jumper> LoadJumperFile()
        {
            jumperList.Clear();

            jumperList.Add(new Jumper { ID = 0, Name = "n/a", Country = ctrlCountry.FindCountry("n-a") });

            var xml = XDocument.Load(jumperFile).Descendants("jumper").ToList();

            xml.ForEach(x => jumperList.Add(
                new Jumper
                {
                    Name = x.Element("name").Value.ToString(),
                    Rank = Int32.Parse(x.Element("rank").Value.ToString()),
                    Current = Int32.Parse(x.Element("current").Value.ToString()),
                    Total = Int32.Parse(x.Element("total").Value.ToString()),
                    ID = Int32.Parse(x.Element("id").Value.ToString()),
                    Country = ctrlCountry.FindCountry(x.Element("country").Value.ToString())
                })
                );

            return jumperList;
        }

        public static CtrlJumper Instance
        {
            get
            {
                lock (padlock)
                {
                    if (instance == null)
                    {
                        instance = new CtrlJumper();
                    }

                    return instance;
                }
            }
        }

        public List<Jumper> GetJumpers()
        {
            return jumperList;
        }
    }
}